package com.jackchong.base

import android.view.View
import com.chad.library.adapter.base.BaseQuickAdapter
import com.jackchong.net.JBaseData
import com.jackchong.net.CacheStrategy
import com.jackchong.net.JNet.net
import com.jackchong.net.JNetParam
import com.jackchong.net.NetLoadingMode
import io.reactivex.Observable

/**
 * author : jack(黄冲)
 * e-mail : 907755845@qq.com
 * create : 2020/9/14
 * desc   :
 */
abstract class KtEntrustRefreshFragment<T, M> : KtRefreshFragment() {

    abstract val adapter: BaseQuickAdapter<M, *>

    abstract val api: Observable<out JBaseData<T>>

    abstract fun conversion(it: T?): MutableList<M>?

    open val getCacheStrategy: CacheStrategy = CacheStrategy.NOT()

    override fun onRefresh() {
        load()
    }

    override fun onLoadMore() {
        load()
    }

    override fun initLayout(view: View) {
        onRefresh()
    }

    private fun load(){
        net(api, JNetParam.build {
            view = this@KtEntrustRefreshFragment
            loadingMode = NetLoadingMode.HIDE
            strategy = getCacheStrategy
            onNext = {
                if (page == DEFAULT_PAGE) {
                    adapter.setList(conversion(it))
                }else{
                    val conversion = conversion(it)
                    if (conversion != null){
                        adapter.addData(conversion)
                    }
                }
            }
            onComplete = {
                finishRefreshAndLoadMore(adapter)
            }
        })
    }
}